@file:OptIn(ExperimentalFoundationApi::class)

package wang.xinqiu.mysqlcontrol.ui

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import wang.xinqiu.mysqlcontrol.data.ConnectionInfo
import wang.xinqiu.mysqlcontrol.data.MySQLManager
import wang.xinqiu.mysqlcontrol.data.QueryResult
import androidx.compose.ui.text.style.TextOverflow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TableViewScreen(
    connectionInfo: ConnectionInfo,
    databaseName: String,
    tableName: String,
    mysqlManager: MySQLManager,
    onBack: () -> Unit,
    onSessionExpired: (() -> Unit)? = null
) {
    val context = LocalContext.current
    
    var queryResult by remember { mutableStateOf<QueryResult?>(null) }
    var isLoading by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var currentPage by remember { mutableStateOf(1) }
    var totalRows by remember { mutableStateOf(0) }
    
    val pageSize = 15
    
    fun loadTableData(page: Int) {
        isLoading = true
        errorMessage = null
        
        (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
            // 获取总行数
            val countQuery = "SELECT COUNT(*) FROM `$tableName`"
            val countResult = mysqlManager.executeQuery(databaseName, countQuery)
            
            if (countResult.isSuccess) {
                val count = countResult.getOrNull()?.rows?.firstOrNull()?.firstOrNull()?.toIntOrNull() ?: 0
                totalRows = count
                
                // 获取分页数据
                val offset = (page - 1) * pageSize
                val dataQuery = "SELECT * FROM `$tableName` LIMIT $pageSize OFFSET $offset"
                val dataResult = mysqlManager.executeQuery(databaseName, dataQuery)
                
                isLoading = false
                
                if (dataResult.isSuccess) {
                    queryResult = dataResult.getOrNull()
                } else {
                    errorMessage = dataResult.exceptionOrNull()?.message
                    if (errorMessage?.contains("会话已过期") == true) {
                        onSessionExpired?.invoke()
                    }
                }
            } else {
                isLoading = false
                errorMessage = countResult.exceptionOrNull()?.message
                if (errorMessage?.contains("会话已过期") == true) {
                    onSessionExpired?.invoke()
                }
            }
        }
    }
    
    LaunchedEffect(Unit) {
        loadTableData(currentPage)
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("$tableName - $databaseName") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    IconButton(onClick = { loadTableData(currentPage) }) {
                        Icon(Icons.Default.Refresh, contentDescription = "刷新")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            // 分页信息
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "总计 $totalRows 行",
                    style = MaterialTheme.typography.bodyMedium
                )
                
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    IconButton(
                        onClick = { 
                            if (currentPage > 1) {
                                currentPage--
                                loadTableData(currentPage)
                            }
                        },
                        enabled = currentPage > 1 && !isLoading
                    ) {
                        Icon(Icons.Default.ChevronLeft, contentDescription = "上一页")
                    }
                    
                    Text(
                        text = "第 $currentPage 页",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    
                    IconButton(
                        onClick = { 
                            val totalPages = (totalRows + pageSize - 1) / pageSize
                            if (currentPage < totalPages) {
                                currentPage++
                                loadTableData(currentPage)
                            }
                        },
                        enabled = currentPage < (totalRows + pageSize - 1) / pageSize && !isLoading
                    ) {
                        Icon(Icons.Default.ChevronRight, contentDescription = "下一页")
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 数据显示区域
            Card(
                modifier = Modifier.fillMaxSize()
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp)
                ) {
                    when {
                        isLoading -> {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator()
                            }
                        }
                        errorMessage != null -> {
                            Card(
                                colors = CardDefaults.cardColors(
                                    containerColor = MaterialTheme.colorScheme.errorContainer
                                )
                            ) {
                                SelectionContainer {
                                    Text(
                                        text = "错误: $errorMessage",
                                        modifier = Modifier.padding(16.dp),
                                        color = MaterialTheme.colorScheme.onErrorContainer,
                                        fontFamily = FontFamily.Monospace
                                    )
                                }
                            }
                        }
                        queryResult != null -> {
                            TableDataView(queryResult!!)
                        }
                        else -> {
                            Text(
                                text = "暂无数据",
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun TableDataView(result: QueryResult) {
    var selectedRowIndex by remember { mutableStateOf<Int?>(null) }
    var showContentDialog by remember { mutableStateOf(false) }
    var dialogContent by remember { mutableStateOf("") }
    var dialogTitle by remember { mutableStateOf("") }
    
    if (result.columns.isNotEmpty() && result.rows.isNotEmpty()) {
        // 使用单个 LazyRow 包含整个表格
        LazyRow {
            items(result.columns.indices.toList()) { columnIndex ->
                Column {
                    // 表头
                    Card(
                        modifier = Modifier
                            .width(150.dp)
                            .height(48.dp)
                            .padding(1.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.primaryContainer
                        )
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = result.columns[columnIndex],
                                modifier = Modifier.padding(8.dp),
                                style = MaterialTheme.typography.labelMedium,
                                color = MaterialTheme.colorScheme.onPrimaryContainer
                            )
                        }
                    }
                    
                    // 该列的所有数据
                    result.rows.forEachIndexed { rowIndex, row ->
                        val cellContent = if (columnIndex < row.size) row[columnIndex] else ""
                        
                        Card(
                            modifier = Modifier
                                .width(150.dp)
                                .height(48.dp)
                                .padding(1.dp)
                                .combinedClickable(
                                    onClick = { 
                                        selectedRowIndex = if (selectedRowIndex == rowIndex) null else rowIndex
                                    },
                                    onDoubleClick = {
                                        dialogContent = cellContent
                                        dialogTitle = "${result.columns[columnIndex]} (第${rowIndex + 1}行)"
                                        showContentDialog = true
                                    }
                                ),
                            colors = CardDefaults.cardColors(
                                containerColor = if (selectedRowIndex == rowIndex) 
                                    MaterialTheme.colorScheme.secondaryContainer 
                                else 
                                    MaterialTheme.colorScheme.surface
                            )
                        ) {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = cellContent,
                                    modifier = Modifier.padding(8.dp),
                                    style = MaterialTheme.typography.bodySmall,
                                    fontFamily = FontFamily.Monospace,
                                    color = if (selectedRowIndex == rowIndex)
                                        MaterialTheme.colorScheme.onSecondaryContainer
                                    else
                                        MaterialTheme.colorScheme.onSurface,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            }
                        }
                    }
                }
            }
        }
    } else {
        Text(
            text = "表为空",
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
    
    // 内容详情弹窗
    if (showContentDialog) {
        AlertDialog(
            onDismissRequest = { showContentDialog = false },
            title = { Text(dialogTitle) },
            text = {
                SelectionContainer {
                    Text(
                        text = dialogContent,
                        fontFamily = FontFamily.Monospace,
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            },
            confirmButton = {
                TextButton(onClick = { showContentDialog = false }) {
                    Text("关闭")
                }
            }
        )
    }
}